package com.sinux.generality.basesupport.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class JsonConf extends BaseConf{
	public JsonConf(String extension){
        try {
//            LogUtil.getLogger().info(resourcePath);
//            List<String> confList = SystemUtil.getFiles(resourcePath, this.getClass().getSimpleName().split("Conf")[0].toLowerCase());
//            this.confsMap = readPropertiess(readPath());
        	this.paramsMap = readJsons(readPath(extension), extension);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	
	public JSONObject readJsons(List<String> confList,String extension)throws Exception{
		JSONObject map = new JSONObject();
        for(String resourcePath:confList){
            map.put(getKeyword(resourcePath,extension), readXml(resourcePath));
        }
        return map;
    }
	
	public JSONObject readXml(String resourcePath)throws Exception{
//      InputStream is = this.getClass().getResourceAsStream(resourcePath);
		JSONObject map = new JSONObject();
		//读取json文件
		FileReader fileReader = null;
		Reader reader = null;
		String jsonStr = null;
        try {
            File jsonFile = new File(resourcePath);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            map = JSON.parseObject(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally{
        	if(reader != null){
        		reader.close();
        	}
        	if(fileReader != null){
        		fileReader.close();
        	}
        }
		return map;
  }
}
